﻿using System.IO;
using System.Net;
using System.Text;
using Abp.Dependency;
using Abp.Runtime.Session;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;

namespace AbpProjectTemplate.Web.Logs
{
    public static class LogExtensions
    {
        public static void UseLogBrowser(this IApplicationBuilder app)
        {
            //日志目录访问，需要验证登录
            var logRootPath = Path.Combine(Path.GetDirectoryName(typeof(LogExtensions).Assembly.Location), "Logs");
            if (Directory.Exists(logRootPath))
            {
                var fileServerOptions = new FileServerOptions()
                {
                    FileProvider = new PhysicalFileProvider(logRootPath),
                    RequestPath = "/Logs",
                    EnableDirectoryBrowsing = true,
                };
                var contentTypeProvider = new FileExtensionContentTypeProvider();
                // Add new mappings
                contentTypeProvider.Mappings[".log"] = "text/plain;charset=UTF-8";
                fileServerOptions.StaticFileOptions.ContentTypeProvider = contentTypeProvider;
                //fileServerOptions.StaticFileOptions.OnPrepareResponse = async (ax) =>
                //{

                //    var session = IocManager.Instance.Resolve<IAbpSession>();

                //    if (!session.UserId.HasValue)
                //    {
                //        ax.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                //        await ax.Context.Response.WriteAsync("没有权限");
                //        await ax.Context.Response.CompleteAsync();
                //    }
                //};
                //验证登录
                app.Use(async (http, next) =>
                {
                    if (http.Request.Path.StartsWithSegments(fileServerOptions.RequestPath, System.StringComparison.OrdinalIgnoreCase))
                    {
                        var session = IocManager.Instance.Resolve<IAbpSession>();

                        if (!session.UserId.HasValue)
                        {
                            http.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                            await http.Response.WriteAsync("没有权限", Encoding.UTF8);
                            return;
                        }
                    }
                    await next(http);
                    // In the case of HTTP request (not secure), end the pipeline here.
                }); 
                app.UseFileServer(fileServerOptions);
            }
        }
    }
}
